/**
 * @param {string} s
 * @return {string}
 */
 var robotWithString = function(s) {
    let map = new Array(26).fill(0);
    let stack = [],res = '';
    for(let i = 0; i < s.length; i++){
        map[s[i].charCodeAt() - 97]++;
    }
    const doPop = ()=>{
        for(let i = 0; i < 26; i++){
            if(map[i] > 0){
                while(stack.length && stack[stack.length - 1].charCodeAt() - 97 <= i) res += stack.pop();
                break;
            }
        }
    };
    for(let i = 0; i < s.length; i++){
        stack.push(s[i]);
        map[s[i].charCodeAt() - 97]--;
        doPop();
    }
    res += stack.reverse().join('');
    return res;
};
let s = "zza";
s = "bac";
s = "bdda";
console.log(robotWithString(s));